<?php


namespace app\api\controller;


use app\common\controller\Api;
use app\common\model\Serviceorder as OrderModel;

/**
 * 服务订单接口
 * Class ServiceOrder
 * @package app\api\controller
 */
class ServiceOrder extends Api
{
    public function _initialize()
    {
        $this->noNeedRight = '*';
        parent::_initialize();
    }

    /**
     * 订单列表
     *
     * @ApiMethod (POST)
     * @ApiParams (name="page", type="string", required=false, description="分页页码, 默认1")
     * @ApiParams (name="limit", type="string", required=false, description="分页, 每页数据条数, 默认10")
     * @ApiParams (name="status", type="string", required=true, description="订单状态")
     */
    public function list()
    {
        $user = $this->auth->getUser();
        $page = $this->request->post('page', 1);
        $limit = $this->request->post('limit', 10);
        $status = $this->request->post('status', '');
        $model = new OrderModel();
        if ($status !== '') {
            if ($status == 2) {
                $model = $model->whereIn('status', [2, 3, 4]);
            } else {
                $model = $model->where('status', $status);
            }
        }
        $model = $model->where('user_id', $user['id']);
        $data = $model->with(['detail' => ['service', 'expert'], 'address'])->page($page, $limit)->order('createtime', 'desc')->select();
        $this->success(__('Operation completed'), $data);
    }

    /**
     * 订单详情
     *
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="string", required=true, description="订单id")
     */
    public function detail()
    {
        $user = $this->auth->getUser();
        $id = $this->request->post('id');
        if (empty($id)) {
            $this->error(__('Invalid parameters'));
        }
        $orderModel = new OrderModel();
        $order = $orderModel->with(['detail' => ['service', 'expert'], 'address'])->where('id', $id)->where('user_id', $user['id'])->find();
        if (!$order) {
            $this->error(__('Order not exist'));
        }
        $data = $order;
        $this->success(__('Operation completed'), $data);
    }

    /**
     * 取消订单
     *
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="string", required=true, description="订单id")
     */
    public function cancel()
    {
        $user = $this->auth->getUser();
        $id = $this->request->post('id');
        if (empty($id)) {
            $this->error(__('Invalid parameters'));
        }
        $orderModel = new OrderModel();
        $order = $orderModel->where('id', $id)->where('user_id', $user['id'])->find();
        if (!$order) {
            $this->error(__('Order not exist'));
        }
        $order->status = -1;
        $order->save();
        $this->success(__('Cancel Success'));
    }
}